package cn.kgc.shiro.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/3/26
 * @description shiro安全框架的配置类
 */
@Configuration
public class ShiroWebConfig {


    // 将shiro中提供的filter对象 托管到spring容器中
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置安全管理器对象
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 设置过滤器 拦截的路径
        LinkedHashMap<String, String> pathMap = new LinkedHashMap<>();
        // authc 是 FormAuthenticationFilter 过滤器的缩写     anon  AnonymousFilter  匿名访问
        // 添加拦截路径和过滤器对应关系时  要注意顺序  首先先存入放行的资源
        pathMap.put("/user/login", "anon");
        pathMap.put("/**", "authc");

        shiroFilterFactoryBean.setLoginUrl("/user/toLogin");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(pathMap);
        return shiroFilterFactoryBean;
    }

    // 将安全管理器托管到spring容器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }

    // 将自定义的域对象托管到spring容器
    @Bean
    public CustomerRealm customerRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        //创建hash类型的凭证匹配器
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(10);
        customerRealm.setCredentialsMatcher(md5);
        return customerRealm;
    }

}
